const host = `http://www.union.yhdengdeng.net/api/mini`
const commonHost = `http://www.union.yhdengdeng.net/api`
export default {
	request(data) {
		if (data.url[0] == '/') {
			data.url = `${commonHost}${data.url}`
		} else {
			data.url = `${host}/${data.url}`
		}
		data.header = {
			Accept: `application/json`,
		}
		// data.headers = {
		// 	'Content-Type': 'multipart/form-data'
		// }

		const token = uni.getStorageSync('token');
		if (token) {
			data.header.Authorization = `Bearer ` + uni.getStorageSync('token')
		}

		return uni.request(data).then(data => {

			var [error, res] = data
			if (res.statusCode >= 200 && res.statusCode < 300) {
				//成功返回时，获取后台message的值
				if (res.data.message) {
					uni.showToast({
						title: `${res.data.message}`,
						icon: 'success',
						duration: 2000
					})
				}
				return res.data
			}
			//提交数据
			if (res.statusCode == 422) {
				let content = Object.entries(res.data.errors).map(([key, e]) => e.join('\n')).join(
					'\r\n');
				uni.showModal({
					title: '提示：提交数据错误',
					content,
					showCancel: false,
					confirmText: '确定'
				})
				return Promise.reject();
			}
			// 未登录
			if (res.statusCode == 401) {
				uni.removeStorageSync('token');
				uni.reLaunch({
					url: '/pages/login/index.vue'
				})
			}
			if (res.statusCode > 499) {
				uni.showToast({
					title: `${res.data.message}`,
					icon: 'error',
					duration: 2000
				})
			}

			return Promise.reject(res)

		});
	},
	get(url, params = {}) {
		if (Object.keys(params).length) {
			url += '?' + Object.entries(params).map((v, k) => k + '=' + v).json('&')
		}
		return this.request({
			url
		})
	},
	post(url, data = {}) {
		return this.request({
			url,
			data,
			method: 'POST'
		})
	},
	put(url, data = {}) {
		return this.request({
			url,
			data,
			method: 'PUT'
		})
	},
	delete(url) {
		return this.request({
			url,
			method: 'DELETE'
		})
	}
}
